package org.cos.verifier.ui;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;

import org.cos.verifier.process.Rule;
import org.cos.verifier.process.RuleManager;

public class RuleEditorDlg extends Frame {
	RuleEditorDlg me = null;
	TextField name_box;
	TextArea describ_box;
	TextArea content_box;
	Panel ctrl_panel,cnt_panel, title_panel;
	Button save_btn, cancel_btn;
	Label title = null;
	RuleEditListDlg parent = null;
	String old_name ;
	
	public RuleEditorDlg() {
		this.me = this;
		title = new Label();
		name_box = new TextField();
		describ_box = new TextArea();
		content_box = new TextArea();
		save_btn = new Button("保存");
		cancel_btn = new Button("取消");
		cnt_panel= new Panel();
		ctrl_panel = new Panel();
		
		ctrl_panel.setLayout(new GridLayout(1, 2));
		ctrl_panel.add(cancel_btn);
		ctrl_panel.add(save_btn);
		cancel_btn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				me.dispose();
			}
		});
		save_btn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				save_rule(me.name_box.getText(), me.describ_box.getText(), me.content_box.getText());
				me.dispose();
			}
		});
		
		cnt_panel.setLayout(new GridLayout(2,1));
		cnt_panel.add(describ_box);
		cnt_panel.add(content_box);
		
		me.setLayout(new BorderLayout());
		me.setSize(500, 400);
		me.add(name_box, BorderLayout.NORTH);
		me.add(ctrl_panel, BorderLayout.SOUTH);
		me.add(cnt_panel, BorderLayout.CENTER);
		me.addWindowListener(new FrameHandler());
	}
	
	private void save_rule(String name,String describ,String content){
		Rule rule = new Rule();
		rule.name = name;
		rule.describ = describ;
		rule.content = content;
		RuleManager.get_inst().set_rule(rule);
		parent.reload();
	}
	
	private void load_rule(String name) {
		Rule r = RuleManager.get_inst().get_rule(name);
		if (r == null)
			return;
		name_box.setText(r.name);
		describ_box.setText(r.describ);
		content_box.setText(r.content);
	}
	
	public void display(RuleEditListDlg parent){
		this.parent = parent;
		if (parent.is_edit){
			load_rule(parent.crr_name);
			old_name = parent.crr_name;
		}
		me.setVisible(true);
	}
	
	class FrameHandler extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			me.dispose();
		}
	}
}
